/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 欢迎到知启蒙网站（https://www.zhiqim.com）购买正版软件，知启蒙还提供许多开源框架和软件。
 * 
 * 1、本软件产品所有源代码受《中华人民共和国著作权法》和其他有关法律、法规的保护，其所有知识产权归湖南知启蒙科技有限公司所有；
 * 2、禁止复制和修改。不得复制修改、翻译或改编本软件所有源代码，或者基于本软件产品创作衍生作品；
 * 3、禁止进行逆向工程。不得对本软件的源代码进行逆向工程、反编译或试图以其他方式发现软件的源代码；
 * 4、个别授权：如需进行商业性的销售、复制、分发，包括但不限于软件销售、预装、捆绑等，必须获得知启蒙的书面授权和许可；
 * 5、保留权利：本注释未明示授权的其他一切权利仍归知启蒙所有，任何人使用其他权利时必须获得知启蒙的书面同意。
*/
package net.redxyz.repost.service.handler;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.redxyz.repost.service.dao.RepostDao;
import net.redxyz.repost.service.dao.UserDao;
import net.redxyz.top.TaobaoService;
import net.redxyz.top.data.item.Item;
import net.redxyz.top.dbo.user.User;
import net.redxyz.top.repost.dbo.AssRepostPlan;
import net.redxyz.top.repost.dbo.AssRepostPlanDetail;
import net.redxyz.top.repost.dbo.AssRepostSchedule;

import org.zhiqim.kernel.control.Handler;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

/**
 * 均衡上架创建处理器
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class RepostPlanHandler implements Handler<AssRepostPlan>
{
    private static final Log log = LogFactory.getLog("timer.repost.log");

    public void process(AssRepostPlan plan)
    {
        String nick = plan.getNick();
        String planId = plan.getPlanId();
        String planWeeks = plan.getPlanWeeks();
        String planHours = plan.getPlanHours();
        String datetime = DateTimes.getDateTimeString();

        try
        {
            log.info("均衡上架计划创建[" + nick + "][" + planId + "]开始");

            // 计划是否授权超时
            User user = UserDao.getUser(nick);
            if (user == null)
            {
                log.error("均衡上架计划创建[" + nick + "][" + planId + "][查询用户信息不存在]...");
                return;
            }

            if (user.getUserStatus() != 0)
            {
                plan.setPlanStatus(2);
                plan.setUpdateTime(datetime);
                ORM.table().update(plan);
                log.error("均衡上架计划创建[" + nick + "][" + planId + "][授权到期禁止调用]...");
                return;
            }

            // 判断是否大于32个ID,如果大于则分段处理，淘宝最大支持32个每次
            List<Item> onsaleItemList = null;
            String sellerCidstr = plan.getPlanSellerCids();
            if (Validates.isEmpty(sellerCidstr))
            {
                onsaleItemList = TaobaoService.getItemService().getOnsaleItemListAll(nick, user.getSessionId(), plan.getPlanSellerCids(), plan.getPlanTitle());
            }
            else
            {
                String[] sellerCids = sellerCidstr.split(",");
                if (sellerCids.length <= 32)
                    onsaleItemList = TaobaoService.getItemService().getOnsaleItemListAll(nick, user.getSessionId(), plan.getPlanSellerCids(),
                        plan.getPlanTitle());
                else
                {
                    // log.info("均衡上架计划创建["+nick+"]["+planId+"]分类数["+sellerCids.length+"]");
                    onsaleItemList = new ArrayList<Item>();

                    // 把CIDS分成每段32个
                    for (int i = 0; i < (sellerCids.length - 1) / 32 + 1; i++)
                    {
                        String scids = "";
                        for (int ii = 0; ii < 32; ii++)
                        {
                            if ((i * 32 + ii) > sellerCids.length - 1)
                                break;// 当最后一段时，需判断是否到最后

                            if (ii != 0)
                                scids += ",";// 非每一个前补逗号

                            scids += sellerCids[i * 32 + ii];
                        }

                        List<Item> thisItemList = TaobaoService.getItemService().getOnsaleItemListAll(nick, user.getSessionId(), scids, plan.getPlanTitle());

                        for (Item item : thisItemList)
                        {// 一个宝贝可能隶属于多个SELLERCIDS，要过滤
                            if (!isContain(onsaleItemList, item))
                                onsaleItemList.add(item);
                        }

                    }

                }
            }

            // 查询符合条件的宝贝
            Selector selector = new Selector();
            selector.addMaybe("nick", user.getNick());
            selector.addMaybeNotEqual("itemStatus", 2);
            selector.addReplace("d", "001");
            List<AssRepostPlanDetail> planDetails = ORM.table().list(AssRepostPlanDetail.class, selector);

            // 查询指定上下架计划宝贝
            List<AssRepostSchedule> repostItemList = ORM.table().list(AssRepostSchedule.class, new Selector("nick", nick));

            // 去除已经存在计划的宝贝
            for (Iterator<Item> it = onsaleItemList.iterator(); it.hasNext();)
            {
                Item item = it.next();
                if (isExists(planDetails, repostItemList, item.getNumIid()))
                    it.remove();

                if (Validates.isEmpty(item.getDelistTime()))
                    it.remove();
            }

            int planItemNum = onsaleItemList.size();
            Updater updater = new Updater();
            updater.addMaybe("planId", plan.getPlanId());
            updater.addField("planItemNum", planItemNum);
            updater.addField("updateTime", datetime);
            ORM.table().update(AssRepostPlan.class, updater);

            // 生成所有宝贝位置
            List<int[]> pos = RepostDao.buildSequence(planWeeks, planHours);

            // 循环把每个宝贝详情放置到详情表
            for (int ind = 0; ind < planItemNum; ind++)
            {
                int[] p = pos.get(ind);
                int planWeek = p[0];
                String planTime = RepostDao.buildRepostTime(p);
                Item onsaleitem = RepostDao.getRepostItem(planWeek, planTime, onsaleItemList);

                AssRepostPlanDetail planDetail = new AssRepostPlanDetail();
                planDetail.setNick(nick);
                planDetail.setPlanId(planId);
                planDetail.setNumIid(onsaleitem.getNumIid());
                planDetail.setCid(onsaleitem.getCid());
                planDetail.setItemTitle(onsaleitem.getTitle());
                planDetail.setItemPicUrl(onsaleitem.getPicUrl());
                planDetail.setItemNum(onsaleitem.getNum());
                planDetail.setItemStatus(0);
                planDetail.setItemSequence(ind);
                planDetail.setDelistTime(onsaleitem.getDelistTime());
                planDetail.setPlanWeek(planWeek);
                planDetail.setPlanTime(planTime);
                planDetail.setOperateStatus(0);
                planDetail.setOperateTime(null);
                planDetail.setOperateDetail(null);

                // 如果手动排除宝贝中存在，则无需调整
                if (Validates.isNotEmpty(plan.getPlanDownIids()) && plan.getPlanDownIids().contains(String.valueOf(onsaleitem.getNumIid())))
                {
                    planDetail.setItemStatus(2);
                    planDetail.setOperateStatus(3);
                }

                ORM.table().replace(planDetail);
            }

            // 再更新最后一个宝贝位置，并置计划生成完成
            Updater updater2 = new Updater();
            updater2.addMust("planId", plan.getPlanId());
            updater2.addField("planStatus", 1);
            updater2.addField("planOperateStatus", 1);
            updater2.addField("planSequence", planItemNum - 1);
            updater2.addField("updateTime", datetime);
            ORM.table().update(AssRepostPlan.class, updater2);

            log.info("均衡上架计划创建[" + nick + "][" + planId + "]成功[" + planItemNum + "]个宝贝");
        }
        catch (Exception e)
        {
            log.error("均衡上架计划创建[" + nick + "][" + planId + "]异常", e);
        }
    }

    private boolean isContain(List<Item> onsaleList, Item item)
    {
        for (Item onsale : onsaleList)
        {
            if (onsale.getNumIid() == item.getNumIid())
                return true;
        }

        return false;
    }

    /**
     * 判断是否加入均衡上下架计划或指定上下架计划
     *
     * @param planDetails
     * @param repostList
     * @param numIid
     * @return
     */
    private boolean isExists(List<AssRepostPlanDetail> planDetails, List<AssRepostSchedule> repostItemList, long numIid)
    {
        for (AssRepostPlanDetail detail : planDetails)
        {
            if (detail.getNumIid() == numIid)
                return true;
        }

        for (AssRepostSchedule item : repostItemList)
        {
            if (item.getNumIid() == numIid)
                return true;
        }

        return false;
    }

}
